import { reqCartList, reqDeleteById, reqUpdateCheckedByid } from "@/api";

const state = {
    cartList: []
};
const mutations = {
    GETCARLIST(state, cartList) {
        state.cartList = cartList
    }
};
const actions = {
    //获取购物车列表数据
    async getCartList({ commit }) {
        let result = await reqCartList();
        if (result.code == 200) {
            commit('GETCARLIST', result.data)
        }
    },
    //删除购物车某一个产品
    async deletCartListBySkuId({ commit }, skuId) {
        let result = await reqDeleteById(skuId)
    },
    //修改购物车某一个产品选中状态
    async updateCheckedById({ commit }, { skuId, isChecked }) {
        let result = await reqUpdateCheckedByid(skuId, isChecked);
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject(new Error('fail'))
        }
    },
    //删除全部勾选的产品
    deleteAllCheckedCart({ dispatch, getters }) {
        //context: 小仓库 ,commit getters dispatch state
        //获取购物车中全部的产品(是一个数组)
        getters.cartList.cartInfoList.forEach(item => {
            let PromiseAll = [];
            let promise = item.isChecked == 1 ? dispatch('deletCartListBySkuId', item.skuId) : '';
            //将每一次返回的Promise添加到数组中
            PromiseAll.push(promise);
        })
        //只要都成功,则结果为成功,如果有一个失败,则返回的是失败的结果
        return Promise.all(PromiseAll)
    },
    //修改全部产品的状态
    updateAllCartChecked({ dispatch, state }, isChecked) {
        let promiseAll = [];
        state.cartList[0].cartInfoList.forEach((item) => {
            
            let promise = dispatch("updateCheckedById", { skuId: item.skuId, isChecked })
            promiseAll.push(promise)
        })
        //最终返回结果
       return Promise.all(promiseAll)
    }
};
const getters = {
    cartList(satte) {
        return state.cartList[0] || {}
    },
};

export default {
    state,
    mutations,
    actions,
    getters
}